﻿using System;
using System.IO;
using System.Linq;
using HappyBa.Core.Interfaces;
using Mnk.Library.Common.Log;
using Mnk.Library.Common.MT;
using ServiceStack.Text;

namespace HappyBa.Core.Data
{
    class DataCache : IDataCache
    {
        private readonly ILog log = LogManager.GetLogger<DataCache>();
        private readonly IDataReceiver dataReceiver;
        private readonly Config config;

        public DataCache(IDataReceiver dataReceiver, Config config)
        {
            this.dataReceiver = dataReceiver;
            this.config = config;
            if (!string.IsNullOrEmpty(config.SelectedProfile))
            {
                try
                {
                    var path = BuildPath(config);
                    if (File.Exists(path))
                    {
                        using (var f = File.OpenRead(path))
                        {
                            Metrics = new Metrics(JsonSerializer.DeserializeFromStream<ReceivedData>(f));
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Write(ex, "Can't read data");
                }
            }
            Metrics = new Metrics(new ReceivedData());
        }

        public IMetrics Metrics { get; private set; }

        public void Collect(IUpdater updater)
        {
            var target = config.Current.Projects.CheckedItems.Select(x => new ProjectInfo(x)).ToArray();
            if (!target.Any())
            {
                log.Write("Nothing to collect");
                return;
            }
            var data = dataReceiver.Receive(updater, target);
            var path = BuildPath(config);
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            if (File.Exists(path)) File.Delete(path);
            using (var f = File.Create(path))
            {
                JsonSerializer.SerializeToStream(data, f);
            }
            Metrics = new Metrics(data);
        }

        private static string BuildPath(Config config)
        {
            return Path.Combine(Folders.UserProfilesFolder, config.UserFolderName, "cache.json");
        }
    }
}
